﻿using Newtonsoft.Json;
using QG.FrontDesk.BLL.IService;
using QG.FrontDesk.com.Models;
using QG.FrontDesk.Model;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace OauthQQ.Controllers
{
    public class QQUserController : Controller
    {

        private IUserInfoService _userInfoService;

        public QQUserController(IUserInfoService userInfoService)
        {
            _userInfoService = userInfoService;
        }

        // GET: QQUser
        public ActionResult Login()
        {
            string state = DateTime.Now.ToString("yyyyMMddHHmmssffff");  //client端的状态值。用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回。
            string url = QQLoginHelper.CreateAuthorizeUrl(state);
            RouteValueDictionary routeValue = RouteData.Route.GetRouteData(this.HttpContext).Values;
            Session["QQLoginState"] = state;    //记录client端状态值
            Session["BeforeLoginUrl"] = "/Home/Index";//记录登陆之前的URL，登陆成功后返回            
            return Redirect(url);
        }
        public ActionResult CallBack()
        {
            string backState = Request.QueryString["state"];
            string code = Request.QueryString["code"];
            if (null != backState && null != code && null != Session["QQLoginState"] && backState == Session["QQLoginState"].ToString())
            {
                Session["QQLoginState"] = null;
                //调获取AccessToken的接口
                string access_token = QQLoginHelper.GetAccessToken(code);
                //调获取OpenID的接口
                string openid = QQLoginHelper.GetOpenId(access_token);
                //调获取用户信息的接口
                QQUserInfo qqUserInfo = QQLoginHelper.GetQQUserInfo(access_token, openid);
                if (qqUserInfo.ret == 0 && string.IsNullOrEmpty(qqUserInfo.msg))
                {
                    //查询该QQ是否存在返回用户信息
                    UserInfo userInfo = _userInfoService.GetUserInfoByQQ(qqUserInfo.nickname);
                    if (userInfo != null)
                    {
                        userInfo.Type = 1;
                    }
                    else//不存在该用户新增用户信息
                    {
                        userInfo = new UserInfo()
                        {
                            UserName = qqUserInfo.nickname,
                            QQ = qqUserInfo.nickname,
                            Sex = qqUserInfo.gender == "男",
                            TouXiang = qqUserInfo.figureurl_qq_2
                        };
                        //赋值给Session
                        if (_userInfoService.AddQQUserInfo(userInfo))
                        {
                            userInfo.Type = 1;
                        };
                    }
                    FormsAuthenticationTicket ticket = null;
                    //拼接要存的管理员id和登录名称
                    string userData = JsonConvert.SerializeObject(userInfo);
                    //数据放入ticket
                    ticket = new FormsAuthenticationTicket(1, "求职", DateTime.Now, DateTime.Now.AddMinutes(60), false, userData);
                    //数据加密
                    string enyTicket = FormsAuthentication.Encrypt(ticket);
                    //创建cookie
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enyTicket);
                    //写入cookie
                    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                }
                else
                {
                    //获取用户失败
                    throw new ApplicationException(qqUserInfo.msg);
                }
                if (Session["BeforeLoginUrl"] != null)
                {
                    return Redirect(Session["BeforeLoginUrl"].ToString()); //返回登陆之前的URL
                }
                else
                {
                    throw new Exception("登录之前的路由丢失");
                }
            }
            else
            {
                throw new Exception("登录State已丢失或不正确");
            }
        }

    }
}